var express = require('express');
var router = express.Router();
var { usermodel } = require( '../module/ljs' );
const Core = require( "@alicloud/pop-core" ); // 引入阿里云 SDK
const bcrypt = require( 'bcryptjs' );
const { log } = require( 'debug/src/browser' );

//验证码登录
// LTAI5tEF1LwYTXMWht9enfPK
// iSZPX61jOG6lIVx9DGDQvJJT3KEK2s
//cwen 对阿里短信服务API进行配置
let client = new Core( {
  accessKeyId: 'LTAI5tEF1LwYTXMWht9enfPK',
  accessKeySecret: 'iSZPX61jOG6lIVx9DGDQvJJT3KEK2s',
  endpoint: 'https://dysmsapi.aliyuncs.com',
  apiVersion: '2017-05-25'
} );
//cwen 请求方式
let requestOption = {
  method: 'POST'
};
//# 生成随机四位数，模拟验证码
function rander( max, min ) {
  return Math.floor( Math.random() * ( max - min ) ) + min
}
//# 存储手机号+验证码（方便验证）
var loginInfo = [];
//# 验证手机号是否已经发送验证码
let validate = ( phone ) => {
  return loginInfo.every( item => item.phone === phone )
}
//# 验证验证码是否一致
let validateCode = ( mobile, captcha ) => {
  return loginInfo.some( item => item.mobile === mobile && item.captcha == captcha );
}
//cwen 用阿里云api发送短信验证(验证码登录)
router.post( "/sendCode", async ( req, res ) => {
  let { mobile } = req.body;
  let randCode = rander( 100000, 999999 );
  var params = {
    PhoneNumbers: mobile, // 客户端手机号
    SignName: "睿智小火龙", //签名
    TemplateCode: "SMS_468385316", //模板，用于发送文字信息
    TemplateParam: JSON.stringify( { 'code': randCode } ) //指定要发送的验证码（此处以rander 函数为例）
  }
  client.request( 'SendSms', params, requestOption ).then( ( result ) => {
    if ( result.Code == 'OK' ) {
      res.send( {
        status: 200,
        msg: '发送成功',
        randCode
      } );
      loginInfo.push( {
        mobile: mobile, // 确保使用相同的数据类型
        captcha: randCode // 确保使用相同的数据类型
      } );
      console.log( loginInfo );
      console.log( randCode )
    } else {
      res.send( {
        status: 400,
        msg: '发送失败'
      } )
    }
  } )
} )



//注册
router.post( "/register", async ( req, res ) => {
  let { mobile, password, captcha, username, email, address } = req.body;
  // 秘文长度
  const hashLen = 10
  const encipherPassword = bcrypt.hashSync( password, hashLen )
  const userByMobile = await usermodel.findOne( { mobile } )
  if ( validateCode( mobile, captcha ) ) { // 判断验证码与手机号是否匹配
    if ( userByMobile ) {
      res.send( {
        status: 201,
        msg: "该用户已存在"
      } )
    } else {
      await usermodel.create( { mobile, password: encipherPassword,username, email, address } )
      res.send( {
        status: 200,
        msg: '注册成功',
      } )
      loginInfo = []; // 注册成功，立马清空数组，以免无法再次发送验证码
    }
  } else {
    res.send( {
      status: 400,
      msg: '验证码错误'
    } )
  }
} )

//密码登录
router.get( "/passwordlogin", async ( req, res ) => {
  let { password, mobile } = req.query
  const findUser = await usermodel.find( { mobile } )
  console.log( findUser, password, mobile );
    // 判断加密后的密码是否相等
 if ( findUser.length != 0 ) {
    const bcryptBL = bcrypt.compareSync( password, findUser[ 0 ].password )
      if ( bcryptBL && mobile === findUser[0].mobile ) {
        res.send( {
          status: 200,
          msg: "登录成功",
          findUser:findUser[0]
        } )
      } else {
        res.send( {
          status: 202,
          msg: "手机号或密码错误"
        } )
      }
    } else{
      res.send( {
        status: 201,
        msg: "该账号不存在，请注册"
      } )
    }
} )


//验证码登录接口
router.post( "/phoneCodeLogin", async ( req, res ) => {
  let { mobile, captcha } = req.body;
  let findUser = await usermodel.find( { mobile } )
  if ( validateCode( mobile, captcha ) ) { // 判断验证码与手机号是否匹配
    if ( findUser.length == 0 ) {
      res.send( {
        status: 201,
        msg: "该账号不存在，请注册"
      } )
    } else {
      res.send( {
        status: 200,
        msg: '登录成功',
        findUser:findUser[0]
      } )
      loginInfo = []; // 登录成功，立马清空数组，以免无法再次发送验证码
    }
  } else {
    res.send( {
      status: 202,
      msg: '验证码错误'
    } )
  }
} )

module.exports = router

